package com.hz.framework.common.util.encrypt;

import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.SM4;
import java.nio.charset.StandardCharsets;


/**
 * @Author: zzx
 * @Date: 2024/9/30 17:03
 */
public class SM4Util {
    /**SM4密钥（16进制字符串形式）**/
    private static final String HEX_KEY = "55fb2ef96cd95db18f90a8a86af77ef4";

    private static final SM4 SM_4;

    /**类加载时利用静态代码块初始化SM4实例**/
    static {
        byte[] bytes = HexUtil.decodeHex(HEX_KEY);
        SM_4 = new SM4(Mode.ECB, Padding.PKCS5Padding,bytes);
    }

    /**
     * 解密
     * @param value
     * @return
     */
    public static String decrypt(String value){
        String str ="";
        try {
            str = SM_4.decryptStr(value, StandardCharsets.UTF_8);
        }catch (Exception e){
            str = value;
        }
        return str;
    }

    /**
     * 加密
     * @param value
     * @return
     */
    public static String encrypt(String value){
        if(StrUtil.isBlank(value)){
            return value;
        }
        return SM_4.encryptHex(value);
    }

    public static void main(String[] args) {

        System.out.println(decrypt("52d355a072cdb696b3461952782f6ab0"));
        System.out.println(decrypt("5de2dc0f5782316a2ac93b487d0eedd8"));
        System.out.println(encrypt("张老三"));
        System.out.println(encrypt("李老四"));
    }
   /* public static void main(String[] args) {
        // 创建SM4加密对象
        SymmetricCrypto sm4 = SmUtil.sm4();

        // 生成密钥
        byte[] keyBytes = sm4.getSecretKey().getEncoded();
        String a = HexUtil.encodeHexStr(keyBytes);
        System.out.println(a);
    }*/

}
